package com.stu.manager.organization.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.stu.manager.config.Result;
import com.stu.manager.organization.entity.SysRoom;
import com.stu.manager.organization.entity.dto.RoomDto;
import com.stu.manager.organization.mapper.SysRoomMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-02-13
 */
@Service
public class SysRoomServiceImpl extends ServiceImpl<SysRoomMapper, SysRoom> implements IService<SysRoom> {

    //模糊查询加分页
    public IPage<SysRoom> pageRoom(Page<SysRoom> pageRoom, QueryWrapper<SysRoom> wrapper) {
        IPage<SysRoom> sysRoomIPage = baseMapper.selectPage(pageRoom, wrapper);
        return sysRoomIPage;
    }

    //添加教室
    public Result addRoom(RoomDto roomDto) {
        String roomAddr = roomDto.getRoomAddr();
        QueryWrapper<SysRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("room_addr",roomAddr);
        Integer count = baseMapper.selectCount(wrapper);
        if(count > 0){
            return Result.error().message("当前教室已添加！");
        }

        SysRoom sysRoom = new SysRoom();
        BeanUtils.copyProperties(roomDto,sysRoom);
        int insert = baseMapper.insert(sysRoom);
        if (insert > 0) {
            return Result.ok().message("添加成功！");
        } else {
            return Result.error().message("添加失败！");
        }
    }

    //查询一个教室信息
    public SysRoom getRoomById(String id) {
        QueryWrapper<SysRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        SysRoom sysRoom = baseMapper.selectOne(wrapper);
        return sysRoom;
    }

    //修改班级信息
    public Result updateRoom(SysRoom sysRoom) {
        String roomAddr = sysRoom.getRoomAddr();
        QueryWrapper<SysRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("room_addr",roomAddr).ne("id",sysRoom.getId());
        Integer count = baseMapper.selectCount(wrapper);
        if(count> 0){
            return Result.error().message("当前添加教室地址已存在");
        }

        int i = baseMapper.updateById(sysRoom);
        if(i>0){
            return Result.ok().message("修改成功！");
        }else {
            return Result.error().message("修改失败！");
        }
    }

    //查询所有教室
    public List<SysRoom> getAllRoom() {
        List<SysRoom> sysRooms = baseMapper.selectList(null);
        return sysRooms;
    }
}
